<?php
namespace app\manage\controller;

class RebateRule extends Base
{
    public function index(){
        if(request()->isAjax()){
            $gameId = input('game_id');
            $page = input('page');
            $limit = input('limit');
            $id = input('id');

            $where = [];
            !empty($gameId) && $where[] = ['exp',"FIND_IN_SET({$gameId}, gamelist)"];
            !empty($id) && $where['id'] = $id;

            if( ! $count=model('RebateRule')->where($where)->count() ){
                $this->layTable();
            }

            $select = model('RebateRule')
                ->where($where)
                ->order('addtime desc')
                ->limit(($page-1)*$limit, $limit)
                ->select();

            $this->layTable(0, '返利规则', $select, $count);
        }else{
            return view();
        }
    }

    public function add(){
        if(request()->isAjax()){
            $data['gamelist'] = input('gamelist');
            $data['name'] = input('name');
            $data['rule'] = input('rule');
            $data['type'] = input('type');
            $date = input('datetime');
            $arr = explode(' - ', $date);
            $data['starttime'] = $arr[0];
            $data['endtime'] = $arr[1];

            if( ! model('RebateRule')->checkRule($data['rule']) ){
                $this->layJson(1, '返利规则错误');
            }

            $addRs = model('RebateRule')->save( $data );

            $addRs ? $this->layJson(0, '添加成功') : $this->layJson(1, '添加失败，请重试');
        }else{
            $gameNotice = model('Game')->gameNotice();
            return view('', ['gameNotice'=>$gameNotice]);
        }
    }

    public function edit(){
        if( request()->isAjax() ){
            $data['id'] = input('id');
            $data['gamelist'] = input('gamelist');
            $data['name'] = input('name');
            $data['rule'] = input('rule');
            $data['type'] = input('type');
            $date = input('datetime');
            $arr = explode(' - ', $date);
            $data['starttime'] = $arr[0];
            $data['endtime'] = $arr[1];
            $editRs = model('RebateRule')->isUpdate(true)->save( $data );
            $editRs!==false ? $this->layJson(0, '编辑成功') : $this->error(1, '编辑失败，请重试');
        }else{
            $find = model('RebateRule')->find( input('id') );
            $gameNotice = model('Game')->gameNotice();
            return view('', ['find'=>$find, 'gameNotice'=>$gameNotice]);
        }
    }

    public function del(){
        model('RebateRule')->destroy(input('id')) ? $this->layJson(0, '删除成功') : $this->error(1, '删除失败，请重试');
    }
}